package com.yuyou.fn.platform.service.impl;

import com.github.wens.mybatisplus.examples.Example;
import com.yuyou.fn.platform.entity.SysUser;
import com.yuyou.fn.platform.mapper.SysUserMapper;
import com.yuyou.fn.common.util.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import com.yuyou.fn.platform.mapper.SysUserRoleMapper;
import com.yuyou.fn.platform.entity.SysUserRole;
import com.yuyou.fn.platform.service.ISysUserRoleService;
import com.github.wens.framework.service.impl.SuperServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * SysUserRole 表数据服务层接口实现类
 *
 */
@Service
public class SysUserRoleServiceImpl extends SuperServiceImpl<SysUserRoleMapper, SysUserRole,Long> implements ISysUserRoleService {



    @Override
    public List<SysUserRole> findRoleByUserId(Long userId) {
        Example<SysUserRole> example = SysUserRole.createExample();
        example.createCriteria().andEqualTo("userId" , userId );
        return findListByExample(example);
    }

    @CacheEvict(value = "CacheOfResource",key = "#userId")
    @Transactional
    @Override
    public void saveOrUpdateUserRole(List<Long> roleIds, Long userId) {

        if(roleIds == null){
            throw new IllegalArgumentException("Invalid roleIds");
        }

        //del old
        Example<SysUserRole> example = SysUserRole.createExample();
        example.createCriteria().andEqualTo("userId" , userId );
        deleteByExample(example);

        if(roleIds.isEmpty()){
            return ;
        }

        List<SysUserRole> list  = new ArrayList<>();
        for(Long roleId : roleIds ){
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(roleId);
            sysUserRole.setUserId(userId);
            list.add(sysUserRole);
        }
        insertBatch(list);
    }

    @Override
    public void deleteUserRole(Long userId, Long roleId) {

        Example<SysUserRole> example = SysUserRole.createExample();
        Example.Criteria criteria = example.createCriteria();
        if(userId != null){
            criteria.andEqualTo("roleId" , roleId );
        }

        if(roleId != null ){
            criteria.andEqualTo("userId",userId );
        }

        deleteByExample(example);

    }

    @Override
    public List<Long> findSysUserByRoleId(Long roleId) {
        Example<SysUserRole> example = SysUserRole.createExample();
        example.createCriteria().andEqualTo("roleId" , roleId );
        return BeanUtils.toList(findListByExample(example),"userId");
    }
}